package com.demo.file;

import cn.hutool.core.io.FileUtil;

import java.io.*;
import java.nio.channels.FileChannel;
import java.nio.file.Files;
import java.nio.file.StandardCopyOption;


public class FileCopy {

    /**
     * hutoo工具
     * @param source
     * @param target
     * @throws IOException
     */
    public void copy(String source, String target) throws IOException {
        FileUtil.copy(source, target, true);
    }


    /**
     * IO流拷贝
     * @param source
     * @param dest
     * @throws IOException
     */
    public void copy1(String source, String dest) throws IOException {
        int bufferSize = 1024 * 8;
        try (
                InputStream in = new FileInputStream(new File(source));
                OutputStream out = new FileOutputStream(new File(dest));
             ){
            byte[] buffer = new byte[bufferSize];
            int len;
            while ((len = in.read(buffer)) > 0) {
                out.write(buffer, 0, len);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * nio的Files工具拷贝
     * @param source
     * @param target
     * @throws IOException
     */
    public void copy2(String source, String target) throws IOException {
        Files.copy(new File(source).toPath(), new File(target).toPath(), StandardCopyOption.REPLACE_EXISTING);
        //Files.copy(new File(source).toPath(), new File(target).toPath());
    }

    /**
     * channel拷贝
     * @param source
     * @param target
     * @throws IOException
     */
    public void copy3(String source, String target) throws IOException {
        try (
                FileChannel in = new FileInputStream(new File(source)).getChannel();
                FileChannel out = new FileInputStream(new File(target)).getChannel();
                ) {
            in.transferTo(0, in.size(), out);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
